package com.sf.osms.dep.quartz;


import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.stereotype.Component;

import com.sf.osms.dep.processor.util.ExceptionUtils;
import com.sf.osms.dep.processor.util.ResourceUtils;
@Component
public class AgentScanThread extends Thread implements ApplicationListener<ContextRefreshedEvent>{
	
	private static Logger logger = LoggerFactory.getLogger(AgentScanThread.class);
	/**
	 * 默认扫描代理的周期10分钟
	 */
	private static final Integer AGENT_SCAN_PERIOD = 1;
	private ApplicationContext context;
	
	/**
	 * 单位为分钟
	 */
	private Integer agentScanPeriod;
	
	public AgentScanThread(ApplicationContext context,Integer agentScanPeriod){
		this.context = context;
		this.agentScanPeriod = agentScanPeriod;
	}
	
	public AgentScanThread() {
		
	}

	@Override
	public void run() {
		/*try {
    		Thread.sleep(20*60*1000);//延迟2分种 启动
		} catch (InterruptedException e) {
			logger.warn("AgentScanThread sleep exception",e);
		}*/
    	while(true){
    		logger.info("******AgentScanThread start to scan agents*****");
    		DynamicScheduleFactory.dynamicAddAgentEventJob(context);
    		logger.info("******AgentScanThread have been end to scan agents*****");
    		try {
				Thread.sleep(agentScanPeriod*60*1000);//扫描时间间隔
			} catch (InterruptedException e) {
				logger.warn("AgentScanThread sleep exception",e);
			}
    	}
	}

	@Override
	public void onApplicationEvent(ContextRefreshedEvent event) {
		logger.info("......scan thread start");
		if(event.getApplicationContext().getParent() == null){
			logger.info("scan thread start");
			String agentScanPeriodStr =  ResourceUtils.getApplicationConfig("dep.scan.agent");
			Integer agentScanPeriod = AGENT_SCAN_PERIOD;
			if(StringUtils.isNotBlank(agentScanPeriodStr)){
				try {
					agentScanPeriod = Integer.valueOf(agentScanPeriodStr);
				} catch (Exception e) {
					logger.error(ExceptionUtils.getExceptionStackString(e));
					agentScanPeriod = AGENT_SCAN_PERIOD;
				}
				
			}
			AgentScanThread agentScanThread = new AgentScanThread(event.getApplicationContext(),agentScanPeriod);
			agentScanThread.start();
			
        }
	}
	
}
